import winston from 'winston';

/**
 * Middleware that handle cors headers
 * @param  {Context}   ctx
 * @param  {Function}  next
 */
export default async function corsMiddleware(ctx, next) {
    let req = ctx.request;

    // The client will receive CORS related headers only if
    ctx.set('Access-Control-Allow-Origin', '*');

    // Custom headers will be exposed to the "js client",
    // The browser will receive those headers anyway
    ctx.set('Access-Control-Expose-Headers', 'ErrorCode, X-ServerTime');

    // Set header: "Access-Control-Max-Age", in seconds
    // The Access-Control-Allow-Credentials HTTP response header
    // indicates whether the response to request can be exposed
    // when the credentials flag is true. When part of the
    // response to an preflight request it indicates that the
    // actual request can be made with credentials
    ctx.set('Access-Control-Max-Age', 3600);

    ctx.set('Access-Control-Allow-Methods', 'GET, POST');

    // 临时添加 SysOpenID, WxOpenID
    ctx.set('Access-Control-Allow-Headers', 'Authorization, uid, _u, courseid, sessionId, X-Request-With, Content-Type');

    if (ctx.method === 'OPTIONS') {
        // Return 204 for preflight request
        return ctx.status = 204;
    }

    await next();
}
